package com.ecar.api.rest.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import redis.clients.jedis.Jedis;

import com.ecar.common.dto.DataBean;
import com.ecar.common.util.HttpClientUtil;
import com.ecar.common.util.StringUtil;
import com.ecar.api.rest.AbstractResource;
import com.ecar.api.support.dto.FlightExistInfo;
import com.ecar.api.support.dto.FlightInfo;
import com.ecar.api.support.util.Props;
import com.ecar.api.support.util.Redis;

/**
 * 类FlightController.java的实现描述：实现航班信息相关业务处理
 * 
 * @author zcw 2017-10-22
 */
@Controller
@Scope("prototype")
@Path("/flight")
public class FlightController extends AbstractResource {

	// 接机接口
	@GET
	@Path("/{flightNo}/overFlight")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean overFlight(@PathParam("flightNo") String flightNo) {
		Jedis jed = null;
		try {
			jed = Redis.getResource();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Boolean isExists = jed.exists(flightNo);// 查看该次查询的航班号是否存在缓存中
		String flightInfo; // 航班信息
		String key = Props.getValue("flight.jh.ss.key");// 第三方接口密匙
		String url = Props.getValue("flight.jh.sk.url");// 第三方接口地址
		String urlAll;
		String ArrEstimated = null;
		String DepEstimated = null;
		FlightInfo info = new FlightInfo();
		if (isExists == true) { // 首先去缓存里查找
			flightInfo = jed.get(flightNo);
			JSONObject object = JSONObject.fromObject(flightInfo);// 转化为JSON类
			Object jsonobj = new JSONTokener(object.get("result").toString()).nextValue();
			if (jsonobj instanceof JSONObject) {
				String arrCity = JSONObject.fromObject(object.get("result")).getString("ArrCode");
				if (arrCity.equals("WUH")) {
					JSONObject jo = JSONObject.fromObject(object.get("result"));
					ArrEstimated = (String) jo.get("ArrEstimated");
					DepEstimated = (String) jo.get("DepEstimated");
					info.setFlightNo((String) jo.get("FlightNo"));
					info.setArrCity((String) jo.get("ArrCity"));
					info.setDepCity((String) jo.get("DepCity"));
					info.setRate((String) jo.get("Rate"));
				} else {
					return new DataBean(400, "该航班目的地不在武汉");
				}
			} else if (jsonobj instanceof JSONArray) {
				JSONArray json = JSONArray.fromObject(object.get("result").toString());
				for (int i = 0; i < json.size(); i++) {
					JSONObject job = json.getJSONObject(i);
					if (job.get("ArrCode").equals("WUH")) {// 筛选到达地为武汉的数据
						// JSONObject jo =
						// JSONObject.fromObject(job.get("result"));
						ArrEstimated = (String) job.get("ArrEstimated");
						DepEstimated = (String) job.get("DepEstimated");
						info.setFlightNo((String) job.get("FlightNo"));
						info.setArrCity((String) job.get("ArrCity"));
						info.setDepCity((String) job.get("DepCity"));
						info.setRate((String) job.get("Rate"));
						break;
					}
				}
				if (ArrEstimated == null) {
					return new DataBean(400, "该航班到达地不在武汉");
				}
			}
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
			Date date;
			try {
				date = format.parse(DepEstimated);
				info.setDepEstimated(date);
				date = format.parse(ArrEstimated);
				info.setArrEstimated(date);
				return new DataBean(200, info);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			urlAll = new StringBuffer(url).append("?").append("flightNo=").append(flightNo).append("&key=").append(key)
					.toString();
			log.info("开始调航班信息接口,地址为:" + urlAll);
			String jsonResult = HttpClientUtil.httpGet(urlAll);
			JSONObject object = JSONObject.fromObject(jsonResult);// 转化为JSON类
			// JSONObject object = JSONObject.fromObject(jsonResult);//转化为JSON类
			String code = object.getString("error_code");// 得到错误码
			String resultCode = "";
			if ("0".equals(code)) {
				resultCode = object.getString("resultcode");
			}
			if (resultCode.equals("200")) {
				jed.append(flightNo, jsonResult); // 查询结果存入缓存
				jed.expire(flightNo, 3600); // 设置缓存时间为一个小时以防止用户重复查询消耗调取接口次数
				Object jsonobj = new JSONTokener(object.get("result").toString()).nextValue();
				if (jsonobj instanceof JSONObject) {
					String arrCity = JSONObject.fromObject(object.get("result")).getString("ArrCode");
					if (arrCity.equals("WUH")) {
						// ArrEstimated = (String) JSONObject.fromObject(
						// object.get("result")).get("ArrEstimated");
						JSONObject jo = JSONObject.fromObject(object.get("result"));
						ArrEstimated = (String) jo.get("ArrEstimated");
						DepEstimated = (String) jo.get("DepEstimated");
						info.setFlightNo((String) jo.get("FlightNo"));
						info.setArrCity((String) jo.get("ArrCity"));
						info.setDepCity((String) jo.get("DepCity"));
						info.setRate((String) jo.get("Rate"));
					} else {
						return new DataBean(400, "该航班目的地不在武汉");
					}
				} else if (jsonobj instanceof JSONArray) {
					JSONArray json = JSONArray.fromObject(object.get("result").toString());
					for (int i = 0; i < json.size(); i++) {
						JSONObject job = json.getJSONObject(i);
						if (job.get("ArrCode").equals("WUH")) {// 筛选到达地为武汉的数据
							// ArrEstimated = (String) job.get("ArrEstimated");
							// JSONObject jo =
							// JSONObject.fromObject(job.get("result"));
							ArrEstimated = (String) job.get("ArrEstimated");
							DepEstimated = (String) job.get("DepEstimated");
							info.setFlightNo((String) job.get("FlightNo"));
							info.setArrCity((String) job.get("ArrCity"));
							info.setDepCity((String) job.get("DepCity"));
							info.setRate((String) job.get("Rate"));
							break;
						}
					}
					if (ArrEstimated == null) {
						return new DataBean(400, "该航班到达地不在武汉");
					}
				}
				try {
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
					Date date;
					try {
						date = format.parse(DepEstimated);
						info.setDepEstimated(date);
						date = format.parse(ArrEstimated);
						info.setArrEstimated(date);
						return new DataBean(200, info);
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				if (code.equals("209902")) {
					return new DataBean(400, "参数错误，无该航班信息。");
				}
				if (code.equals("10020")) {
					return new DataBean(500, "查询航班接口维护中。。。");
				}
				if (code.equals("209903")) {
					return new DataBean(500, "查询航班接口升级中。。。");
				}
			}
		}
		return null;
	}

	// 送机接口
	@GET
	@Path("/{flightNo}/toFlight")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean toFlight(@PathParam("flightNo") String flightNo) {
		Jedis jed = null;
		try {
			jed = Redis.getResource();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Boolean isExists = jed.exists(flightNo);// 查看该次查询的航班号是否存在缓存中
		String flightInfo; // 航班信息
		String key = Props.getValue("flight.jh.ss.key");// 第三方接口密匙
		String url = Props.getValue("flight.jh.sk.url");// 第三方接口地址
		String urlAll;
		String ArrEstimated = null;
		String DepEstimated = null;
		FlightInfo info = new FlightInfo();
		if (isExists == true) {
			flightInfo = jed.get(flightNo);
			JSONObject object = JSONObject.fromObject(flightInfo);// 转化为JSON类
			Object jsonobj = new JSONTokener(object.get("result").toString()).nextValue();
			if (jsonobj instanceof JSONObject) {
				String depCity = JSONObject.fromObject(object.get("result")).getString("DepCode");
				if (depCity.equals("WUH")) {
					JSONObject jo = JSONObject.fromObject(object.get("result"));
					ArrEstimated = (String) jo.get("ArrEstimated");
					DepEstimated = (String) jo.get("DepEstimated");
					info.setFlightNo((String) jo.get("FlightNo"));
					info.setArrCity((String) jo.get("ArrCity"));
					info.setDepCity((String) jo.get("DepCity"));
					info.setRate((String) jo.get("Rate"));
				} else {
					// return new DataBean(400, "该航班出发地不在武汉");
					return new DataBean(400, "", "该航班出发地不在武汉");
				}
			} else if (jsonobj instanceof JSONArray) {
				JSONArray json = JSONArray.fromObject(object.get("result").toString());
				for (int i = 0; i < json.size(); i++) {
					JSONObject job = json.getJSONObject(i);
					if (job.get("DepCode").equals("WUH")) {// 筛选出发地为武汉的数据
						// JSONObject jo =
						// JSONObject.fromObject(job.get("result"));
						ArrEstimated = (String) job.get("ArrEstimated");
						DepEstimated = (String) job.get("DepEstimated");
						info.setFlightNo((String) job.get("FlightNo"));
						info.setArrCity((String) job.get("ArrCity"));
						info.setDepCity((String) job.get("DepCity"));
						info.setRate((String) job.get("Rate"));
						break;
					}
				}
				if (DepEstimated == null) {
					return new DataBean(400, "", "该航班出发地不在武汉");
					// return new DataBean(400, "该航班出发地不在武汉");
				}
			}
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
			Date date;
			try {
				date = format.parse(DepEstimated);
				info.setDepEstimated(date);
				date = format.parse(ArrEstimated);
				info.setArrEstimated(date);
				// return new DataBean(200, info);
				return new DataBean(200, info, "查询成功");
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			urlAll = new StringBuffer(url).append("?").append("flightNo=").append(flightNo).append("&key=").append(key)
					.toString();
			log.info("开始调航班信息接口,地址为:" + urlAll);
			String jsonResult = HttpClientUtil.httpGet(urlAll);
			JSONObject object = JSONObject.fromObject(jsonResult);// 转化为JSON类
			// JSONObject object = JSONObject.fromObject(jsonResult);//转化为JSON类
			String code = object.getString("error_code");// 得到错误码
			String resultCode = "";
			if ("0".equals(code)) {
				resultCode = object.getString("resultcode");
			}
			if (resultCode.equals("200")) {
				jed.append(flightNo, jsonResult); // 查询结果存入缓存
				jed.expire(flightNo, 3600); // 设置缓存时间为一个小时以防止用户重复查询消耗调取接口次数
				Object jsonobj = new JSONTokener(object.get("result").toString()).nextValue();
				if (jsonobj instanceof JSONObject) {
					String depCity = JSONObject.fromObject(object.get("result")).getString("DepCity");
					if (depCity.equals("WUH")) {
						JSONObject jo = JSONObject.fromObject(object.get("result"));
						ArrEstimated = (String) jo.get("ArrEstimated");
						DepEstimated = (String) jo.get("DepEstimated");
						info.setFlightNo((String) jo.get("FlightNo"));
						info.setArrCity((String) jo.get("ArrCity"));
						info.setDepCity((String) jo.get("DepCity"));
						info.setRate((String) jo.get("Rate"));
					} else {
						// return new DataBean(400, "该航班出发地不在武汉");
						return new DataBean(400, "", "该航班出发地不在武汉");
					}
				} else if (jsonobj instanceof JSONArray) {
					JSONArray json = JSONArray.fromObject(object.get("result").toString());
					for (int i = 0; i < json.size(); i++) {
						JSONObject job = json.getJSONObject(i);
						if (job.get("DepCity").equals("WUH")) {// 筛选出发地为武汉的数据
							// JSONObject jo =
							// JSONObject.fromObject(job.get("result"));
							ArrEstimated = (String) job.get("ArrEstimated");
							DepEstimated = (String) job.get("DepEstimated");
							info.setFlightNo((String) job.get("FlightNo"));
							info.setArrCity((String) job.get("ArrCity"));
							info.setDepCity((String) job.get("DepCity"));
							info.setRate((String) job.get("Rate"));
							break;
						}
					}
					if (DepEstimated == null) {
						// return new DataBean(400, "该航班出发地不在武汉");
						return new DataBean(400, "", "该航班出发地不在武汉");
					}
				}
				try {
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
					Date date;
					try {
						date = format.parse(DepEstimated);
						info.setDepEstimated(date);
						date = format.parse(ArrEstimated);
						info.setArrEstimated(date);
						// return new DataBean(200, info);
						return new DataBean(200, info, "查询成功");
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				if (code.equals("209902")) {
					// return new DataBean(400, "无该航班信息。");
					return new DataBean(400, "", "无该航班信息。");
				}
				if (code.equals("10020")) {
					// return new DataBean(500, "查询航班接口维护中。。。");
					return new DataBean(500, "", "查询航班接口维护中。。。");
				}
				if (code.equals("209903")) {
					// return new DataBean(500, "查询航班接口升级中。。。");
					return new DataBean(500, "", "查询航班接口升级中。。。");
				}
			}
		}
		return null;
	}

	@POST
	@Path("/getFlightInfo")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean getFlightInfo(JSONObject param) {
		JSONObject paramJson = JSONObject.fromObject(JSONObject.fromObject(param.get("param")).get("fields"));
		String flightNo = paramJson.get("flightNo").toString().replaceAll(" ", "");
		String date = paramJson.get("date").toString();
		String dateStr;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		long lt = new Long(date);
		dateStr = simpleDateFormat.format(new Date(lt));
		
		Jedis jed = null;
		try {
			jed = Redis.getResource();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 查看该次查询的航班号是否存在缓存中
		//Boolean isExists = jed.exists(flightNo + date);
		
		String string = Redis.c.get(Redis.K.FLIGHT_INFO.to(flightNo + dateStr));
		Boolean isExists = false;
		if (StringUtil.isNotEmpty(string)) {
			isExists = true;
		}
		
		String key = Props.getValue("flight.jh.sk.key");
		String url = Props.getValue("flight.jh.sk.url");
		String urlAll;
		
		int tempDay = 3;// 可选未来的天数 当前版本默认3天 以后版本将会取数据库数据
		FlightExistInfo infoDto = new FlightExistInfo();

		if (!isExists) { // 如果缓存里没有该条数据
			urlAll = new StringBuffer(url).append("?").append("key=").append(key).append("&flightDate=").append(dateStr)
					.append("&flightNo=").append(flightNo).toString();
			log.info("开始调航班经停地及起降时间接口,地址为:" + urlAll);

			String jsonResult = HttpClientUtil.httpGet(urlAll);

			if (StringUtil.isEmpty(jsonResult)) {
				return new DataBean(402, new JSONObject(), "航班号错误!");
			}
			log.info("查询航班的信息为:" + jsonResult);
			
			// 设置缓存时间为3天
			Redis.c.setex(Redis.K.FLIGHT_INFO.to(flightNo + dateStr),  Redis.DAY*3, jsonResult);
			JSONObject object = JSONObject.fromObject(jsonResult);// 转化为JSON类
			return getArrScheduled(flightNo, tempDay, infoDto, object);

		} else { // 如果缓存里有该条数据
			String jsonResult = Redis.c.get(Redis.K.FLIGHT_INFO.to(flightNo + dateStr));
			
			JSONObject object = JSONObject.fromObject(jsonResult);// 转化为JSON类
			return getArrScheduled(flightNo, tempDay, infoDto, object);
		}
	}

	private DataBean getArrScheduled(String flightNo, int tempDay, FlightExistInfo infoDto, JSONObject object) {
		String errorCode = object.getString("error_code");
		switch (errorCode) {
		case "0":
			Object resultStr = object.get("result");
			String VIACities = JSONObject.fromObject(JSONObject.fromObject(resultStr).get("VIACities").toString())
					.getString("VIACity");
			JSONArray VIACity = JSONArray.fromObject(VIACities);

			if (VIACity.size() > 2) {

				for (int i = 0; i < VIACity.size(); i++) {
					String city = JSONObject.fromObject(VIACity.get(i)).getString("city");
					String toTime = JSONObject.fromObject(VIACity.get(i)).getString("toTime");
					String fromTime = JSONObject.fromObject(VIACity.get(i)).getString("fromTime");

					if ("WUH".equals(city) && !"1970-01-01T00:00:00".equals(fromTime)) {
						infoDto.setTempDay(tempDay);
						infoDto.setFlightNo(flightNo);
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
						Date d;
						try {
							d = format.parse(fromTime);
							infoDto.setArrScheduled(d);
							return new DataBean(200, infoDto, "查询成功");
						} catch (ParseException e) {
							e.printStackTrace();
						}
						break;
					}

					if ("WUH".equals(city) && "1970-01-01T00:00:00".equals(fromTime)) {
						infoDto.setTempDay(tempDay);
						infoDto.setFlightNo(flightNo);
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
						Date d;
						try {
							d = format.parse(toTime);
							infoDto.setArrScheduled(d);
							return new DataBean(200, infoDto, "查询成功");
						} catch (ParseException e) {
							e.printStackTrace();
						}
						break;
					}
				}

			} else {

				for (int i = 0; i < VIACity.size(); i++) {
					String city = JSONObject.fromObject(VIACity.get(i)).getString("city");
					String toTime = JSONObject.fromObject(VIACity.get(i)).getString("toTime");

					if ("WUH".equals(city) && !"1970-01-01T00:00:00".equals(toTime)) {
						infoDto.setTempDay(tempDay);
						infoDto.setFlightNo(flightNo);
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
						Date d;
						try {
							d = format.parse(toTime);
							infoDto.setArrScheduled(d);
							return new DataBean(200, infoDto, "查询成功");
						} catch (ParseException e) {
							e.printStackTrace();
						}
						break;
					}
				}

			}

			return new DataBean(400, new JSONObject(), "该航班到达地不在武汉");
		default:
			return new DataBean(401, new JSONObject(), "无该航班信息。");
		}
	}

}
